package com.daafan.minilib.activity;

import java.io.File;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.daafan.minilib.R;
import com.daafan.minilib.util.AppUtils;

public class EJournalActivity extends BaseActivity implements View.OnClickListener {

	public static final String						EJOURNAL_URL	= "EJOURNAL_URL";

	@SuppressWarnings("unused")
	private net.tsz.afinal.http.HttpHandler<File>	handler;
	private TextView								tv_progress;
	private Button									btn_ejournal_open_apk;
	private ProgressBar								progressBar;

	private String									apkPath			= AppUtils.getMyCacheDir("apk") + "ejournal.apk";
	private File									fileApk;

	private String									url				= "";
	private String									default_url		= "http://data.iego.net:85/data/ly.apk";

	public static String							SHAREPREFERENCE	= "SHAREPREFERENCE";
	public static String							PROGRESS		= "progress";

	public static String							DOWNLOADING		= "downloading";
	public static String							FINISH			= "downloading";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ejournal);

		initTopBar("电子杂志", R.drawable.back, 0);

		progressBar = (ProgressBar) findViewById(R.id.progressBar_ejournal);
		progressBar.setMax(100);

		tv_progress = (TextView) findViewById(R.id.tv_ejournal_progress);
		btn_ejournal_open_apk = (Button) findViewById(R.id.btn_ejournal_open_apk);
		btn_ejournal_open_apk.setVisibility(View.GONE);

		url = getIntent().getStringExtra(EJOURNAL_URL);
		if (url == null || (url != null && url.equals(""))) {
			url = default_url;
		}

		btn_ejournal_open_apk.setOnClickListener(this);

		SharedPreferences settings = getSharedPreferences(SHAREPREFERENCE, 0); // 获取一个 SharedPreferences 对象
		int progress = settings.getInt(PROGRESS, 0);
		boolean downloading = settings.getBoolean(DOWNLOADING, false);// 这里奇怪为什么是true
		boolean finish = settings.getBoolean(FINISH, false);

		if (finish) {
			fileApk = new File(apkPath);
			btn_ejournal_open_apk.performClick();

			finish();
		} else if (downloading) {
			download();
		} else if (!downloading && !finish) {
			confirmDownload();

		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_ejournal_open_apk:
				boolean hasInstalled = false;

				// apk包名com.longyuan.app2
				Intent intent = new Intent(Intent.ACTION_MAIN, null);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				List<ResolveInfo> appsList = getPackageManager().queryIntentActivities(intent, 0);
				for (int i = 0; i < appsList.size(); i++) {
					ResolveInfo mResolveInfo = appsList.get(i);

					// package name
					String packageName = mResolveInfo.activityInfo.packageName;

					if (packageName.contains("com.longyuan.app2")) {
						hasInstalled = true;

						// class name
						String className = mResolveInfo.activityInfo.name;

						ComponentName mComponentName = new ComponentName(packageName, className);
						Intent intent2 = new Intent();
						if (mComponentName != null) {
							intent2.setComponent(mComponentName);
						}
						startActivity(intent2);
					}
				}

				if (!hasInstalled)
					if (fileApk != null && fileApk.exists()) {
						AppUtils.openAPK(mContext, fileApk);

					} else {
						Toast.makeText(mContext, "未下载完，请稍等", 0).show();
					}

				break;

			default:
				break;
		}
	}

	private void confirmDownload() {
		showConfirmDialog("下载电子杂志", "是否确认下载?", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				download();
			}

		}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
	}

	private void download() {
		FinalHttp fh = new FinalHttp();
		handler = fh.download(url, new AjaxParams(), apkPath, true, new AjaxCallBack<File>() {

			@Override
			public void onStart() {
				SharedPreferences settings = getSharedPreferences(SHAREPREFERENCE, 0); // 获取一个 SharedPreferences 对象
				settings.edit().putBoolean(DOWNLOADING, true).commit();

				tv_progress.setText("正在下载....");
			}

			@Override
			public void onLoading(long count, long current) {
				tv_progress.setText("下载进度：" + current + "/" + count);

				double progress = (double) current / (double) count;
				progressBar.setProgress((int) (progress * 100));

				SharedPreferences settings = getSharedPreferences(SHAREPREFERENCE, 0); // 首先获取一个 SharedPreferences 对象
				settings.edit().putInt(PROGRESS, (int) (progress * 100)).commit();
			}

			@Override
			public void onSuccess(File t) {
				tv_progress.setText(t == null ? "null" : t.getAbsoluteFile().toString());

				fileApk = t;

				if (fileApk != null && fileApk.exists())
					new Handler().postDelayed(new Runnable() {

						Context	context	= getApplicationContext();

						@Override
						public void run() {
							AppUtils.openAPK(context, fileApk);
						}
					}, 1000);

				finish();
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				System.out.println(strMsg + "  errorNo=" + errorNo);

				if (errorNo == 416) {
					finish();
				}
			}

			void finish() {
				progressBar.setProgress(100);
				tv_progress.setText("下载完成.");
				btn_ejournal_open_apk.setVisibility(View.VISIBLE);
				fileApk = new File(apkPath);

				SharedPreferences settings = getSharedPreferences(SHAREPREFERENCE, 0); // 首先获取一个 SharedPreferences 对象
				Editor editor = settings.edit();
				editor.putInt(PROGRESS, 100);
				editor.putBoolean(DOWNLOADING, new Boolean(false));
				editor.putBoolean(FINISH, true);
				editor.commit();
			}
		});
	}

	@Override
	protected void onTopLeftClick() {
		back();
	}
}
